package com.nxy.web;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.github.binarywang.java.emoji.EmojiConverter;
import com.nxy.entity.Message;
import com.nxy.service.MessageService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
@WebServlet("*.msg")
@MultipartConfig
public class MessageServlet extends BaseServlet{
      MessageService ms = new MessageService();

    public void addImg(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/json;charset=UTF-8");
        JSONObject json = new JSONObject();
        PrintWriter out = resp.getWriter();

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);
        sfu.setHeaderEncoding("UTF-8"); // 处理中文问题
        sfu.setSizeMax(10* 1024 * 1024); // 限制文件大小
        String fileName = "";
        try {
            List<FileItem> fileItems = sfu.parseRequest(req);
            JSONArray arr = new JSONArray();     //注意摆放的位置
            for (FileItem item : fileItems) {
                fileName = UUID.randomUUID().toString() + item.getName();
                item.write(new File("/Users/shilongliu/Desktop/img/"+ fileName));
                String imgUrl ="/img/"+fileName;
                arr.add(imgUrl);
            }
            json.put("errno", 0);
            json.put("data", arr);
            System.out.println(arr.size());
            out.print(json.toString());
            System.out.println(json.toString());
            out.flush();
            out.close();
            } catch (Exception e) {
                e.printStackTrace();
                json.put("errno","200");
                json.put("msg","服务器异常");
                out.print(json.toString());
        }
    }

    public void addVideo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/json;charset=UTF-8");
        JSONObject json = new JSONObject();
        PrintWriter out = resp.getWriter();

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);
        sfu.setHeaderEncoding("UTF-8"); // 处理中文问题
        sfu.setSizeMax(1000* 1024 * 1024); // 限制文件大小
        String fileName = "";
        try{
            List<FileItem> fileItems = sfu.parseRequest(req);
            JSONArray arr = new JSONArray();     //注意摆放的位置
            for (FileItem item : fileItems) {
                fileName = UUID.randomUUID().toString() + item.getName();
                item.write(new File("/Users/shilongliu/Desktop/video/"+ fileName));
                String videoUrl ="/video/"+fileName;
                arr.add(videoUrl);
            }
            json.put("errno", 0);
            json.put("data", arr);
            System.out.println(arr.size());
            out.print(json.toString());
            System.out.println(json.toString());
            out.flush();
            out.close();
        }catch (Exception e){
            e.printStackTrace();
            json.put("errno","200");
            json.put("msg","服务器异常");
            out.print(json.toString());
        }

    }

    public void addMessage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String msg = req.getParameter("msg");
        System.out.println(msg);

        EmojiConverter emojiConverter = EmojiConverter.getInstance();
        msg = emojiConverter.toHtml(msg);//将聊天内容进行转义

        Message m = new Message(msg,"","");
        boolean flag = ms.addMessage(m);
        if(flag){
            System.out.println("上传成功");
            //resp.sendRedirect("m_index.jsp");
            //resp.getWriter().println(msg);
        }else{
            System.out.println("上传失败");
        }
    }

    public void queryMessage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        List<Message> list = ms.queryMessage();
        req.setAttribute("list",list);
        //req.getRequestDispatcher("m_index.jsp").forward(req,resp);
        req.getRequestDispatcher("queryReplyByMid.rpl").forward(req,resp);
    }

    public void deleteMessageById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String id = req.getParameter("id");
        Message m = new Message();
        m = ms.queryMessageById(id);
        String html = m.getMsg();
        System.out.println(html);

        String Reg = "(?<=src=\").+?(?=\")";//匹配src="与"之间的图片视频路径
        Pattern p = Pattern.compile(Reg);
        Matcher mc = p.matcher(html);
        List<String> uri = new ArrayList();


        while (mc.find()){
            //System.out.println("测试");
            System.out.println(mc.group(0));
            uri.add(mc.group(0));
        }
        System.out.println("取出来的所有地址为："+uri);
        for(String i : uri){
            File file = new File("/Users/shilongliu/Desktop"+i);
            if(file.exists()){
                file.delete();
                System.out.println("视频和图片删除成功");
            }
        }


        boolean flag = ms.deleteMessage(id);
        if(flag){
            resp.sendRedirect("queryMessage.msg");
        }else{
            req.setAttribute("msg","删除失败");
        }
    }

    public void getOldMessage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String id = req.getParameter("id");
        Message m = new Message();
        m = ms.queryMessageById(id);
        String html = m.getMsg();
        req.setAttribute("msg",html);
        req.setAttribute("id",id);
        req.getRequestDispatcher("m_update.jsp").forward(req,resp);
    }

    public void updateMessage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String msg = req.getParameter("msg");
        String id = req.getParameter("id");
        System.out.println(msg);
        System.out.println("ID是:"+id);

        EmojiConverter emojiConverter = EmojiConverter.getInstance();
        msg = emojiConverter.toHtml(msg);//将聊天内容进行转义

        Message m = new Message(msg,"","");
        m.setMsg(msg);
        m.setId(Integer.valueOf(id));
        boolean flag = ms.updateMessage(m);
        if(flag){
            System.out.println("修改成功");
            //resp.sendRedirect("m_index.jsp");
            //resp.getWriter().println(msg);
        }else{
            System.out.println("修改失败");
        }
    }
}
